package com.lq.schoolshop.realm;


import com.lq.schoolshop.pojo.User;
import com.lq.schoolshop.service.UserService;
import org.apache.log4j.Logger;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;

import java.util.List;

/**
 * @Author
 * @Date2021/1/5 20:20
 * @Version V1.0
 *  Shiro权限认证
 **/
public class UserRealm extends AuthorizingRealm {

    private static String Salt = "lq";

    @Autowired
    private UserService userService;

    @Override
    public String getName() {
        return "userRealm";
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //1.从Token获取用户输入的用户名字
        String username = token.getPrincipal().toString();
        System.out.println("账号:"+username);
        SimpleAuthenticationInfo info = null;
        UsernamePasswordToken token1 = (UsernamePasswordToken) token;

        String Tokennusername = token1.getUsername();
        String Tokenpassword = String.valueOf(token1.getPassword());

        System.out.println("tokenpassword:"+Tokenpassword);
        System.out.println("Tokennusername:"+Tokennusername);

        //2.封装数据到sesion中
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();

        //3.将Token中密码取出进行盐值迭代加密
        Md5Hash md5Hash = new Md5Hash(Tokenpassword, Salt, 1);
        System.out.println("加密密码:"+md5Hash);

        //4.根据姓名和密码去数据库查询 是否有该用户
        User login = userService.login(Tokennusername, md5Hash.toString());
        //5.如果查询不为空，则进行放行
        if(login!=null){
            //用户的信息装入到session中
            session.setAttribute("user",login);
        }else{
            //没有该用户
            throw new UnknownAccountException();
        }
        //6.将从数据库中查询的信息封装到SimpleAuten中
        info = new SimpleAuthenticationInfo(username, login.getPassword(), ByteSource.Util.bytes(Salt), getName());
        return info;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        return null;
    }
}
